package com.woniuxy.charin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.charin.model.entity.InvitationFriend;
import com.woniuxy.charin.model.entity.InvitationIncomeDetail;
import com.woniuxy.charin.model.entity.InvitationInfo;
import com.woniuxy.charin.model.vo.InvitationDetailVO;
import com.woniuxy.charin.service.InvitationInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/invitationInfo")
@Api(tags = "邀请管理")
@Slf4j
public class InvitationInfoController {
    @Autowired
    private InvitationInfoService invitationInfoService;

    @GetMapping("/list")
    @ApiOperation("查询邀请")
    public ResponseEntity<IPage<InvitationInfo>> list(
            @RequestParam(required = false) String invitationCode,
            @RequestParam(required = false) String customersName,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String invitationType,
            @RequestParam(required = false) String rewardStatus,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {

        QueryWrapper<InvitationInfo> queryWrapper = new QueryWrapper<>();

        // Enhanced dynamic query conditions
        if (StringUtils.isNotBlank(invitationCode)) {
            queryWrapper.like("invitation_code", invitationCode);
        }
        if (StringUtils.isNotBlank(customersName)) {
            queryWrapper.like("customers_name", customersName);
        }
        if (StringUtils.isNotBlank(phoneNumber)) {
            queryWrapper.like("phone_number", phoneNumber);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("status", status);
        }
        if (StringUtils.isNotBlank(invitationType)) {
            queryWrapper.eq("invitation_type", invitationType);
        }
        if (StringUtils.isNotBlank(rewardStatus)) {
            queryWrapper.eq("reward_status", rewardStatus);
        }

        queryWrapper.orderByDesc("creation_time");
        return ResponseEntity.ok(invitationInfoService.page(new Page<>(current, size), queryWrapper));
    }


    @GetMapping("/detail/{id}")
    @ApiOperation("获取邀请详情")
    public ResponseEntity<InvitationDetailVO> getDetail(@PathVariable Integer id) {
        InvitationDetailVO detail = new InvitationDetailVO();

        // 设置基本信息
        InvitationInfo invitationInfo = invitationInfoService.getById(id);
        detail.setInvitationInfo(invitationInfo);

        // 设置好友列表
        List<InvitationFriend> friendList = invitationInfoService.getFriendsByInvitationId(id);
        detail.setFriendList(friendList);

        // 设置收益明细
        List<InvitationIncomeDetail> incomeDetails = invitationInfoService.getIncomeDetailsByInvitationId(id);
        detail.setIncomeDetails(incomeDetails);

        // 设置统计信息
        detail.setTotalFriends(friendList != null ? friendList.size() : 0);
        detail.setTotalIncome(calculateTotalIncome(incomeDetails));

        return ResponseEntity.ok(detail);
    }

    // 辅助方法：计算总收益
    private BigDecimal calculateTotalIncome(List<InvitationIncomeDetail> incomeDetails) {
        if (incomeDetails == null || incomeDetails.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return incomeDetails.stream()
                .map(InvitationIncomeDetail::getIncomeAmount)  // 假设 InvitationIncomeDetail 有 getAmount() 方法
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }



    @PostMapping("/saveOrUpdate")
    @ApiOperation("新增或修改邀请")
    public ResponseEntity<Boolean> saveOrUpdate(@RequestBody InvitationInfo invitationInfo) {
        boolean result = invitationInfoService.saveOrUpdate(invitationInfo);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据id删除邀请
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @ApiOperation("根据id删除邀请")
    public ResponseEntity<Boolean> remove(@PathVariable Long id) {
        boolean result = invitationInfoService.removeById(id);
        return ResponseEntity.ok(result);
    }
}
